**Program for matching exactly on covariates--recovering the index variable
**kta, version 1.0 02/14/05
**Syntax: emindex depvar treatment varlist [if] [in] [, id(varname numeric)]

program define emindex
version 8.0

syntax varlist [if] [in] [, id(varname numeric)]
tempvar touse
marksample touse

tokenize `varlist'
local v `1'
local tg `2' 
macro shift
macro shift
local rest `*'


quietly {

preserve
if `"`if'"'~="" | "`in'"~="" {
	keep `if' `in'
}


	keep if `tg'==0 
	rename `v' v0
	egen _n0=count(`id'), by(`rest')
	save "c:\STATADATA\emindex_0.dta",replace
restore

preserve
if `"`if'"'~="" | "`in'"~="" {
	keep `if' `in'
}

	keep if `tg'==1 
	egen _n1=count(`id'), by(`rest')
	gen tid=`id'
	drop `id'
	rename `v' v1
	joinby `rest' using "c:\STATADATA\emindex_0.dta", unmatched(both) _merge(_matches)
	egen numc = count(`id'), by(tid)
	egen _encm = count(`id'), by(`id')
	replace numc=. if tid==.
	gen _eweight = 1/numc
	gen _ratio = _n1/_n0
	save "c:\STATADATA\emindex_0_1.dta",replace

	collapse _matches _encm _ratio (sum) _eweight, by(`id')
	save "c:\STATADATA\ematches_0.dta",replace
	use "c:\STATADATA\emindex_0_1.dta",clear
	replace _eweight=1 if tid~=.
	collapse _matches _eweight _ratio, by(tid)
	rename tid `id' 
	gen _encm=.
	append using "c:\STATADATA\ematches_0.dta"
	drop if `id'==.
	recode _matches 3=1 *=0
	save "c:\STATADATA\ematches_0_1.dta",replace
restore

joinby `id' using "c:\STATADATA\ematches_0_1.dta", unmatched(master) _merge(_check)
drop _check

}

end
